<?php

namespace App\Jobs;

use App\Models\User;
use App\Models\GoldRecord;
use App\Models\GoldPayRecord;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Redis;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;

class UploadGoldProductVoucherJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected User $user;
    protected string $cacheId;

    public function __construct(User $user, $cacheId)
    {
        $this->user = $user;
        $this->cacheId = $cacheId;
    }

    public function handle()
    {
        $recordId = Redis::hGet($this->cacheId, 'gold_record_id');
        $voucher = Redis::hGet($this->cacheId, 'voucher');
        if ($recordId <= 0) return;

        if ($record = GoldRecord::find($recordId)) {

            $resellUserId = Redis::hGet($this->cacheId, 'resell_user_id') ?? 0;
        

            if(empty($record->goldRecordVoucher()->get()->toArray())){
                GoldPayRecord::create([
                    'voucher'=>$voucher,
                    'user_id'=>$this->user->id,
                    'from_user_id'=>$resellUserId,
                    'gold_record_id'=>$recordId
                ]);

            }else{
                $record->goldRecordVoucher()->update([
                     'voucher'=>$voucher,
                ]);

            }
           
        }
    }
}
